package com.mentalhealth.diary.exception;

import com.mentalhealth.diary.common.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Map;
import java.util.HashMap;

/**
 * 全局异常处理器
 * 统一处理所有控制器抛出的异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理通用异常
     */
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e, HttpServletRequest request) {
        // 记录异常日志
        e.printStackTrace();
        
        // 构建错误响应
        Map<String, Object> errorInfo = new HashMap<>();
        errorInfo.put("uri", request.getRequestURI());
        errorInfo.put("method", request.getMethod());
        
        return R.error(500, "服务器内部错误: " + e.getMessage());
    }
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public R<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        return R.error(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理数据库异常
     */
    @ExceptionHandler(SQLException.class)
    public R<?> handleSQLException(SQLException e, HttpServletRequest request) {
        // 记录异常日志
        e.printStackTrace();
        
        return R.error(500, "数据库操作失败: " + e.getMessage());
    }
    
    /**
     * 处理404错误
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public R<?> handle404Exception(NoHandlerFoundException e, HttpServletRequest request) {
        return R.error(404, "请求的资源不存在: " + request.getRequestURI());
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public R<?> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        return R.error(400, "参数错误: " + e.getMessage());
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public R<?> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        // 记录异常日志
        e.printStackTrace();
        
        return R.error(500, "系统错误: 空指针异常");
    }
}